

package tomkitty;

import java.util.*;

public class Tag {
  private String myTag;
  private String myContent;
  private ArrayList<Tag> myChildren;
  private Hashtable<String, String> myAttributes;

  public Tag(String initTag) {
    myTag = initTag;
    myContent = "";
    initLists();
  }
  
  private void initLists() {
    myChildren = new ArrayList<Tag>();
    myAttributes = new Hashtable<String, String>();
  }
  
  public Tag setAttribute(String key, String val) {
    myAttributes.put(key, val);
    return this;
  }
  
  public Hashtable<String, String> getAttributes() {
    return myAttributes;
  }
  
  public Tag setContent(String newContent) {
    myContent = newContent;
    return this;
  }
  
  public String getContent() {
    return myContent;
  }
  
  public Tag add(Tag inTag) {
    myChildren.add(inTag);
    return this;
  }

  public Tag newChild(String tag) {
    Tag t = new Tag(tag);
    add(t);
    return t;
  }

  public String render() {
    //this tag has a closing tag if it has content or children
    if(!myContent.equals("") || myChildren.size() > 0) {
      String returnString = "<" + myTag + generateAttributeList(myAttributes) +
        ">\n" + myContent;
      for(int i = 0; i < myChildren.size(); i++) {
        returnString += myChildren.get(i).render();
      }
      return returnString+generateClosingTag("<"+myTag+">");
    } else {
      return "<"+myTag+generateAttributeList(myAttributes)+"/>\n";
    }
  }
  
  private String generateAttributeList(Hashtable<String, String> attributes) {
    String returnString = "";
    if(attributes.size() > 0) {
      for (Enumeration<String> e = attributes.keys(); e.hasMoreElements() ;) {
        String key = e.nextElement();
        String val = attributes.get(key);
                returnString += " "+key+" = "+"\""+val+"\"";      }
    }
    
    return returnString;
  }
  
  private String generateClosingTag(String openingTag) {
    return "</"+openingTag.substring(1)+"\n";
  }
}
